package com.serkol.ams.service.impl;

import cn.hutool.core.codec.Base62;
import cn.hutool.core.codec.Base64;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.serkol.ams.bean.*;
import com.serkol.ams.entity.Poster;
import com.serkol.ams.entity.PosterDevise;
import com.serkol.ams.entity.Users;
import com.serkol.ams.entity.UsersAuthentication;
import com.serkol.ams.mapper.PosterMapper;
import com.serkol.ams.service.*;
import com.serkol.handler.MyLambdaQueryWrapper;
import com.serkol.utils.ImageUtils;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author pingan
 * @description 针对表【poster】的数据库操作Service实现
 * @createDate 2022-11-08 22:51:00
 */
@Service
public class PosterServiceImpl extends ServiceImpl<PosterMapper, Poster>
        implements PosterService {
    @Value("${upload.host}")
    private String uploadhost;
    @Value("${upload.path}")
    private String uploadpath;
    @Autowired
    private PosterDeviseService deviseService;
    @Autowired
    private PosterImageService imageService;

    @Autowired
    private UsersAuthenticationService authenticationService;


    @Autowired
    private UsersService usersService;

    @Autowired
    private PicturesService picturesService;

    @Autowired
    private GoodsService goodsService;

    @Override
    public MyPage<Map<String, Object>> findByList(int pageSize, int page1) {
        MyLambdaQueryWrapper<Poster> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.select(Poster::getId, Poster::getName, Poster::getType, Poster::getAttr, Poster::getNameUg);
        queryWrapper.orderByDesc(Poster::getId);
        Page<Map<String, Object>> page = new Page<>(page1, pageSize);
        Page<Map<String, Object>> mapPage = this.baseMapper.selectMapsPage(page, queryWrapper);
        return MyPage.parsePage(mapPage);
    }

    @Override
    public List<Map<String, Object>> findByDataList() {
        MyLambdaQueryWrapper<Poster> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.select(Poster::getId, Poster::getName, Poster::getType, Poster::getAttr, Poster::getNameUg);
        queryWrapper.orderByDesc(Poster::getId);

        List<Map<String, Object>> maps = this.baseMapper.selectMaps(queryWrapper);
        return maps;
    }

    @Cacheable(cacheNames = "PosterServiceCreateImage", key = "#key")
    @Override
    public String createImage(String page, int type, Long userId, String pages, String key, long othorid) throws IOException, WxErrorException, URISyntaxException, FontFormatException {

        UsersAuthentication info1 = authenticationService.getInfo();
        Users byUserId = usersService.findByUserId(userId);
        File file = picturesService.invalidQrCode(key, pages);
        ImageInfo info = new ImageInfo();
        info.setNickname(byUserId.getNickname());

      //  info.setQrcode(file);
        if (info1 != null) {
            info.setAuthName(info1.getName());
        }
        info.setAvatar(byUserId.getAvatar());

        if (othorid > 0 && type == 1) {
            info = goodsGetById(othorid, info);
        }


        Map<String, Object> image = imageService.findByGetTypeRand(type);
        Object id = image.get("id");
        long l = Long.parseLong(id.toString());
        ImageUtils imageUtils = new ImageUtils();
        String dirpath = uploadpath + "" + image.get("url");
        QueryWrapper<PosterDevise> listquery = new QueryWrapper<>();
        listquery.lambda().eq(PosterDevise::getPosterId, l);
        List<PosterDevise> list = deviseService.list(listquery);
        BufferedImage image1 = imageUtils.createImage(uploadpath, dirpath, list, info);
        //  ImageIO.write(image1, "png",);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ImageIO.write(image1, "png", stream);
        String base64 = Base64.encode(stream.toByteArray());
        stream.flush();
        stream.close();
        return base64;
    }

    @Cacheable(cacheNames = "PosterServiceCreateImageNoType", key = "#othorid")
    @Override
    public String createImage(Long userId, String pages, long othorid) throws IOException, WxErrorException, URISyntaxException, FontFormatException {

        UsersAuthentication info1 = authenticationService.getInfo();
        Users byUserId = usersService.findByUserId(userId);
        File file = picturesService.invalidQrCode(othorid + "poster", pages);
        ImageInfo info = new ImageInfo();
        info.setNickname(byUserId.getNickname());

     //   info.setQrcode(file);
        if (info1 != null) {
            info.setAuthName(info1.getName());
        }
        info.setAvatar(byUserId.getAvatar());


        Map<String, Object> image = imageService.findByGetId(othorid);
        Object id = image.get("id");
        long l = Long.parseLong(id.toString());
        ImageUtils imageUtils = new ImageUtils();
        String dirpath = uploadpath + "" + image.get("url");
        QueryWrapper<PosterDevise> listquery = new QueryWrapper<>();
        listquery.lambda().eq(PosterDevise::getPosterId, l);
        List<PosterDevise> list = deviseService.list(listquery);
        BufferedImage image1 = imageUtils.createImage(uploadpath, dirpath, list, info);
        //  ImageIO.write(image1, "png",);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ImageIO.write(image1, "png", stream);
        String base64 = Base64.encode(stream.toByteArray());
        stream.flush();
        stream.close();
        return base64;
    }

    @Override
    public String myQrcode(int type, Long userId) throws IOException, WxErrorException, URISyntaxException, FontFormatException {
        UsersAuthentication info1 = authenticationService.getInfo();
        Map<String, Object> byUserId = usersService.findBySuorceId(userId);
        String page = "pages/index/index";
        String color = "#000000";
        int ttyoe = 12;
        if (type == 1) {
            page = "page/usercenter/pages/payment/pay";
            ttyoe = 13;
            color = "#e70012";
        }
        if (type == 2) {
            page = "pages/index/regester";

            ttyoe = 14;
            color = "#0e6eb8";
        }
        if (type == 3) {
            page = "pages/index/index";

            ttyoe = 15;
            color = "#0e6eb8";
        }

        String pages = page + "?type=" + ttyoe + "&userId=" + userId;
        String key = Base62.encode(pages);
        File file = picturesService.invalidQrCode(key, pages);
        ImageInfo info = new ImageInfo();
        if (byUserId.containsKey("nickname")) {
            info.setNickname(byUserId.get("nickname").toString());
        }
        if (byUserId.containsKey("invite")) {
            info.setInvalid(byUserId.get("invite").toString());
        }
        if (byUserId.containsKey("agentName")) {
            info.setTitle(byUserId.get("agentName").toString());
        }
       info.setQrcodeFile(file);
        if (info1 != null) {
            info.setAuthName(info1.getName());
        }
        if (byUserId.containsKey("avatar")) {
            info.setAvatar(byUserId.get("avatar").toString());
        }
        List<PosterDevise> list = new ArrayList<>();
        PosterDevise qrcode = new PosterDevise();
        qrcode.setType("image");
        qrcode.setW(530);
        qrcode.setH(530);
        qrcode.setY(580);
        qrcode.setX(330);
        qrcode.setKeyName("qrcode");
        qrcode.setRadius(0);

        list.add(qrcode);
        Integer fontSize = 40;
        Integer fontNameSize = 50;
        PosterDevise name = new PosterDevise();

        name.setType("text");
        name.setW(250);
        name.setH(250);
        name.setY(1440);
        if (info1 != null) {
            name.setX(720 - (info.getAuthName().length() * (fontNameSize)));
        }
        name.setColor(color);
        name.setKeyName("authName");
        name.setFontSize(fontNameSize);


        PosterDevise invalid = new PosterDevise();

        invalid.setType("text");
        invalid.setW(250);
        invalid.setH(250);
        invalid.setY(1540);
        invalid.setColor(color);
        invalid.setKeyName("invite");
        invalid.setFontSize(fontSize);

        PosterDevise title = new PosterDevise();

        title.setType("text");
        title.setW(250);
        title.setH(250);
        title.setY(1540);

        title.setColor(color);
        title.setKeyName("title");
        title.setFontSize(fontSize);
/*        if (LangValidUtils.getValid("ug")) {
            invalid.setY(1520);
            title.setY(1520);
            title.setX(1090 - (info.getTitle().length() * fontSize));
            int xx = 1190 - (1090 - (info.getInvalid().length() / fontSize));

            invalid.setX(xx);
        } else {*/
        invalid.setX(300);
        title.setX(820);
        //  }

        list.add(name);
        if (type == 2) {
            list.add(invalid);
            list.add(title);
        }
        System.out.println(info);
        ImageUtils imageUtils = new ImageUtils();
        String dirpath = getFileName(type);

        BufferedImage image1 = imageUtils.createImage(uploadpath, dirpath, list, info);
        //  ImageIO.write(image1, "png",);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ImageIO.write(image1, "png", stream);
        String base64 = Base64.encode(stream.toByteArray());
        stream.flush();
        stream.close();
        return base64;

    }

    @Cacheable(cacheNames = "PosterServiceCreateImageUserId", key = "#userId")
    @Override
    public String regesterQrcode(Long userId) throws WxErrorException, IOException {

        String page = "pages/index/regester";
        int type = 2;
        String color = "#000000";
        int ttyoe = 14;

        String pages = page + "?type=" + ttyoe + "&userId=" + userId;
        String key = Base62.encode(pages);
        File file = picturesService.invalidQrCode(key, pages);
        String dirpath = getFileName(type);
        BufferedImage bufferedImage = ImageIO.read(file);
        //  ImageIO.write(image1, "png",);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "png", stream);
        String base64 = Base64.encode(stream.toByteArray());
        stream.flush();
        stream.close();
        return base64;
    }

    private String getFileName(int type) {
        String fileName = type == 1 ? "pay" : "invalid";
   /*     if (LangValidUtils.getValid("ug")) {
            fileName = fileName + "Ug.jpg";

        } else {*/
        fileName = fileName + ".jpg";


        String file = uploadpath + "assets/img/" + fileName;
        System.out.println(file);
        return file;
    }

    private ImageInfo goodsGetById(long id, ImageInfo info) {

        Map<String, Object> goods = goodsService.findByMapId(id);
        info.setGoodName(goods.get("name").toString());
        info.setGoodsImage(goods.get("image").toString());
        //info.setGoodName(goods.get("name").toString());
        info.setPrice(new BigDecimal(goods.get("price").toString()));
        return info;
    }

    @Cacheable(cacheNames = "PosterServiceSharePosterNoType", key = "#userId+':users:'+#pages+'page:'+#othorid")
    @Override
    public Map<String, Object> sharePoster(Long userId, String pages, long othorid) throws WxErrorException, IOException {

        UsersAuthentication info1 = authenticationService.getInfo();
        Users byUserId = usersService.findByUserId(userId);
        String file = picturesService.invalidQrCodeUrl(othorid + "poster" + userId, pages);
        ImageInfo info = new ImageInfo();
        info.setNickname(byUserId.getNickname());

        info.setQrcode(file);
        if (info1 != null) {
            info.setAuthName(info1.getName());
        }
        info.setAvatar(byUserId.getAvatar());

        Map<String, Object> image = imageService.findByGetId(othorid);
        Object id = image.get("id");
        String url = (String) image.get("url");
        info.setPosterImage(url);
        long l = Long.parseLong(id.toString());

        QueryWrapper<PosterDevise> listquery = new QueryWrapper<>();
        listquery.lambda().eq(PosterDevise::getPosterId, l);
        List<PosterDevise> list = deviseService.list(listquery);
        ImageInfoRect imageInfoRect = new ImageInfoRect();
        imageInfoRect.posterDevise(url); //"http://localhost/bgdevise.png"

        for (PosterDevise x : list) {

            imageInfoRect.add(x, info);
        }
        System.out.println(imageInfoRect);
        return Map.of("pics", imageInfoRect.getPics(), "texts", imageInfoRect.getTexts());
    }

  //  @Cacheable(cacheNames = "PosterServiceSharePosterNoType", key = "#userId+':users:'+#pages+'page:rand:'+#type")
    @Override
    public Map<String, Object> sharePosterRand(Long userId, String pages, int type, long otherId) throws WxErrorException, IOException {
        UsersAuthentication info1 = authenticationService.getInfo();
        Users byUserId = usersService.findByUserId(userId);
        String file = picturesService.invalidQrCodeUrl(type + "poster" + userId, pages);
        ImageInfo info = new ImageInfo();
        System.out.println(type+"--------------HHH------------------"+otherId);
        if(type==1 && otherId>0){
            System.out.println("--------------HHH------------------");
          //  info = goodsGetById(otherId, info);
            Map<String, Object> goods = goodsService.findByMapId(otherId);
            info.setGoodName(goods.get("name").toString());
            info.setGoodsImage(goods.get("image").toString());
            //info.setGoodName(goods.get("name").toString());
            info.setPrice(new BigDecimal(goods.get("price").toString()));
        }
        info.setNickname(byUserId.getNickname());

        info.setQrcode(file);
        if (info1 != null) {
            info.setAuthName(info1.getName());
        }
        info.setAvatar(byUserId.getAvatar());


        Map<String, Object> image = imageService.findByGetTypeRand(type);
        Object id = image.get("id");
        String url = (String) image.get("url");
        info.setPosterImage(url);
        long l = Long.parseLong(id.toString());

        QueryWrapper<PosterDevise> listquery = new QueryWrapper<>();
        listquery.lambda().eq(PosterDevise::getPosterId, l);
        List<PosterDevise> list = deviseService.list(listquery);
        ImageInfoRect imageInfoRect = new ImageInfoRect();
        imageInfoRect.posterDevise(url); //"http://localhost/bgdevise.png"

        for (PosterDevise x : list) {

            imageInfoRect.add(x, info);
        }
        System.out.println(imageInfoRect);
        System.out.println(info);
        return Map.of("pics", imageInfoRect.getPics(), "texts", imageInfoRect.getTexts());
    }

}




